# 将redis中爬取的课程数据保存到mongo
import json
import redis
import pymongo

def main():
    print("正在链接数据库...")
    # 指定Redis数据库信息
    rediscli = redis.StrictRedis(host='localhost', port=6379, db=0)
    # 指定MongoDB数据库信息
    mongocli = pymongo.MongoClient(host='localhost', port=27017)
    print("创建数据库...")
    # 创建数据库名
    db = mongocli['csdn']
    # 创建空间
    sheet = db['course']
    print("等待写入，从redis读取数据，写入mongo")
    while True:
        # FIFO模式为 blpop，LIFO模式为 brpop，获取键值
        source, data = rediscli.blpop(["course_spider:items"])
        print("读取到集合",source,data)
        if source:
            item = json.loads(data)
            sheet.insert(item)

            try:
                print(u"Processing: %(title)s" % item)
            except KeyError:
                print(u"Error procesing: %r" % item)
        else:
            break

if __name__ == '__main__':
    main()